package com.cheng.chengrobot.handler.gptHandler;


import com.cheng.chengrobot.domain.GptChatHistory;
import com.cheng.chengrobot.service.GroupService;
import com.cheng.chengrobot.service.RobotService;
import com.cheng.chengrobot.service.gpt.GptChatHistoryService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import net.mamoe.mirai.event.EventHandler;
import net.mamoe.mirai.event.SimpleListenerHost;
import net.mamoe.mirai.event.events.GroupMessageEvent;
import net.mamoe.mirai.message.data.*;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class GroupGptHandler
        extends SimpleListenerHost
{

    @Value("${gpt.api-key}")
    private String apiKey;

    @Value("${gpt.system-message}")
    private String systemMessage;

    @Autowired
    @Qualifier("proxyOkHttp")
    private OkHttpClient.Builder okHttpClientBuilder;

    @Autowired
    private GptChatHistoryService gptChatHistoryService;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private GroupService groupService;

    @Autowired
    private RobotService robotService;

    @EventHandler
    public void handleGroupMessage(@NotNull GroupMessageEvent event)
            throws Exception
    {
        //判断是否qq号的gpt和群gpt功能都开着
        if (!(groupService.isChatGptTurnedOn(event.getBot().getId(), event.getGroup().getId())
                && robotService.isChatGptTurnedOn(event.getBot().getId()))) return;


        //合成消息的字符串
        MessageChain messageChain = event.getMessage();
        String messageStr = "";
        for (SingleMessage singleMessage : messageChain)
        {
            if (singleMessage instanceof At) continue;

            messageStr += singleMessage.contentToString();
        }
        //制作消息记录持久化存储到数据库
        GptChatHistory gptChatHistory = new GptChatHistory();
        gptChatHistory.setMessage(messageStr);
        gptChatHistory.setRole("user");
        gptChatHistory.setRobotQq(event.getBot().getId());
        gptChatHistory.setGroupQq(event.getSubject().getId());
        gptChatHistory.setQq(event.getSender().getId());

        this.gptChatHistoryService.insert(gptChatHistory);

        //制作请求体，选取过去的5轮对话
        //构建json节点
        ObjectNode requestBodyJson = objectMapper.createObjectNode().put("model", "gpt-3.5-turbo");
        ArrayNode messagesJson = objectMapper.createArrayNode();
        //加入系统消息
        messagesJson.add(objectMapper.createObjectNode()
                                 .put("role", "system")
                                 .put("content", systemMessage));

        List<GptChatHistory> gptMemories = this.gptChatHistoryService.selectRecentTen(event.getBot().getId(),
                                                                                      event.getSubject().getId(),
                                                                                      event.getSender().getId());
        //循环往节点里面加入消息
        for (int i = 0;i < gptMemories.size();i++)
        {
            messagesJson.add(objectMapper.createObjectNode()
                                     .put("role", gptMemories.get(gptMemories.size() - i - 1).getRole())
                                     .put("content", gptMemories.get(gptMemories.size() - i - 1).getMessage()));
        }

        requestBodyJson.set("messages", messagesJson);

        //构建请求对象
        OkHttpClient okHttpClient = okHttpClientBuilder.build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, requestBodyJson.toString());
        Request request = new Request.Builder()
                .url("https://api.openai.com/v1/chat/completions")
                .method("POST", body)
                .addHeader("Authorization", "Bearer " + apiKey)
                //                .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)")
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = null;
        try
        {
            //发送请求
            response = okHttpClient.newCall(request).execute();
            //解析响应体，取出gpt回复
            JsonNode responseBody = null;
            responseBody = objectMapper.readTree(response.body().string());
            System.out.println(requestBodyJson.toString());
            System.out.println(responseBody.toString());

            gptChatHistory.setNull();
            gptChatHistory.setRole(responseBody.get("choices").get(0).get("message").get("role").asText());
            gptChatHistory.setMessage(responseBody.get("choices").get(0).get("message").get("content").asText());
            gptChatHistory.setRobotQq(event.getBot().getId());
            gptChatHistory.setGroupQq(event.getSubject().getId());
            gptChatHistory.setQq(event.getSender().getId());

            //发送至对应群并艾特对应人
            event.getSubject().sendMessage(
                    MessageUtils.newChain(new At(gptChatHistory.getQq()), new PlainText(gptChatHistory.getMessage())));

            this.gptChatHistoryService.insert(gptChatHistory);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        //关闭响应
        if (response != null) response.close();

    }


}
